Skip to content

Reversed a few tight loops#151

Open
mlsomers wants to merge 1 commit intoerikkaashoek:mainfrom
mlsomers:ReverseLoops
Open

Reversed a few tight loops#151
mlsomers wants to merge 1 commit intoerikkaashoek:mainfrom
mlsomers:ReverseLoops

Conversation

@mlsomers
Copy link
Copy Markdown

An old optimization trick: Remove the comparison from the loop.

For example:

int b=1000; // some dynamic large number
for (int i=0; i<b; i++)
  // do something[i]...

The comparison i<b will be done a thousand times.
In assembly it would look like:

LDA i // load i into register A
LDB b // load b into register B
CMP A B // compare registers A and B
JNE ... // Jump non equal

Replace that code with:

int b=1000; // some dynamic large number
for (int i=b-1; i!=0; i--)
  // do something[i]...
// do something[0]...

In assemby the i!=0 comparison looks like

LDA i // load i into register A
JNZ ... // Jump non zero

Which (depending on the compiler, processor and branch prediction) usually results in a faster loop.
Note that the loop does not include zero, so the [0] item will have to be done separately.

Disclaimer: I could not compile, or test these changes, still figuring out how to set this up, I just applied the technique to some random places hoping I would hit a significant one :-)

It is not always worthwhile. Small static loops would be unwind-ed by the compiler. If the stuff inside the loop is extensive then the difference would be insignificant. It usually helps with copying buffers or things like moving the waterfall one pixel down (could not find that part though).

Hope this helps a little, even if it only extends battery life when the processor is not a bottleneck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant